<script setup>
import { map } from 'lodash-es';
import { useWatch } from '@/hooks/useWatch';
import { useRequest } from '@/hooks/requestHooks';
import { getAreaList, getBuildingByArea, getDeviceSys, getBranchType } from '@/api/index.js';
const emit = defineEmits(['handleQuery', 'resetQuery']);
const props = defineProps({
  projectType: { type: String, default: '' },
  propParams: { type: Boolean, default: true },
  deviceSelect: { type: Boolean, default: false },
  institutionType: { type: Boolean, default: false },
  reset: { type: Number, default: 0 },
  isStage: { type: Boolean, default: false },
  showType: { type: Boolean, default: false },
});
const { projectType, propParams, deviceSelect, institutionType } = toRefs(props);
const cascaderRef = ref(null);
const queryForm = ref({
  cascader: [],
  buildingCode: null,
  equSysName: null,
  organizationType: null,
  contractType: null,
  contractTypeCode: null,
});
const cascaderProps = ref({
  emitPath: true,
  checkStrictly: true,
  label: 'areaName',
  value: 'areaName',
});
const currentCode = ref([]);
const [areaList] = useRequest(getAreaList, {
  defaultParams: [{}],
  onSuccess: res => {
    // if (res.data?.length > 0 && props.propParams) {
    //默认山西太原
    queryForm.value.cascader = ['山西省'];
    cascaderChange(queryForm.value.cascader);
    // }
  },
});
const [institutionList, , run] = useRequest(getBuildingByArea, {
  defaultParams: [{ level: '', areaName: '', project_type: projectType.value, isStage: props.isStage ? 1 : null }],
  // manual: true,
  onSuccess: res => {
    currentCode.value = [];
    if (propParams.value) {
      if (queryForm.value.cascader?.length > 0 && props.propParams) {
        if (props.isStage) {
          for (let i = 0; i < res?.data.length; i++) {
            if (res?.data[i].entrustStage === 'OPERATION' || res?.data[i].entrustStage === 'JCOPERATION') {
              queryForm.value.buildingCode = res?.data[i];
              queryForm.value.contractType = res?.data[i]?.contractType;
              queryForm.value.contractTypeCode = res?.data[i]?.contractTypeCode;
              break; // 终止循环
            }
          }
        } else {
          queryForm.value.buildingCode = res.data[0] ?? null;
          queryForm.value.contractType = res.data?.[0]?.contractType;
          queryForm.value.contractTypeCode = res?.data[i]?.contractTypeCode;
        }
        handleQuery();
      }
    }
  },
});
const [deviceList, deviceLoading, deviceRun] = useRequest(getDeviceSys, {
  defaultParams: [],
  manual: true,
  onSuccess: res => {
    queryForm.value.equSysName = res.data[0];
  },
});
const [dwlxLists, insTypeLoading, insTypeRun] = useRequest(getBranchType, {
  manual: true,
});
const findAllNode = data => {
  if (!currentCode.value.includes(data?.label)) {
    currentCode.value.push(data?.label);
  }
  if (data?.parent) {
    findAllNode(data?.parent);
  }
};
const cascaderChange = async value => {
  await nextTick(() => {
    const currentObj = cascaderRef.value.getCheckedNodes()[0];
    findAllNode(currentObj);
  });
  let str = currentCode.value?.reverse()?.join('/');
  const obj = { project_type: projectType.value, areaName: str, isStage: props.isStage ? 1 : null };
  run(obj);
  queryForm.value.buildingCode = null;
};
const selectChange = val => {
  queryForm.value.contractType = val?.contractType;
  queryForm.value.contractTypeCode = val?.contractTypeCode;
};
const handleQuery = () => {
  emit('handleQuery', queryForm.value);
};
const resetQuery = () => {
  queryForm.value.cascader = ['山西省'];
  if (propParams.value) {
    cascaderChange(queryForm.value.cascader);
  } else {
    queryForm.value.buildingCode = null;
    queryForm.value.equSysName = null;
    queryForm.value.organizationType = null;
    run({ level: '', areaName: '山西省', project_type: projectType.value, isStage: props.isStage ? 1 : null });
  }
  if (deviceSelect.value) {
    deviceRun();
  }

  emit('resetQuery', queryForm.value);
};
useWatch(
  deviceSelect,
  n => {
    if (n) {
      deviceRun();
    }
  },
  { immediate: true },
);
useWatch(
  institutionType,
  n => {
    if (n) {
      insTypeRun();
    }
  },
  { immediate: true },
);
useWatch(
  () => props.reset,
  n => {
    resetQuery();
  },
);
</script>
<template>
  <div class="u-mb20">
    <el-form v-model="queryForm" class="u-base-fg u-pl20 u-pt20" inline>
      <el-form-item prop="cascader" label="行政区划">
        <el-cascader ref="cascaderRef" v-model="queryForm.cascader" :props="cascaderProps" :options="areaList"
          placeholder="请选择行政区划" size="small" @change="cascaderChange" style="width: 230px"></el-cascader>
      </el-form-item>
      <el-form-item prop="buildingCode" label="机构名称">
        <el-select size="small" v-model="queryForm.buildingCode" value-key="enterpriseCode" placeholder="请输入机构名称"
          style="width: 350px" @change="selectChange" filterable>
          <el-option v-for="(val, index) in institutionList" :key="`${val.enterpriseCode}-${index}`"
            :label="val.enterpriseName" :value="val"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-show="deviceSelect" prop="equSysName" label="设备系统名称">
        <el-select size="small" v-model="queryForm.equSysName" placeholder="请选择设备系统名称" style="width: 230px"
          :loading="deviceLoading">
          <el-option v-for="val in deviceList" :key="val" :label="val" :value="val"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-show="institutionType" label="机构类型：">
        <el-select class="el-input_search" v-model="queryForm.organizationType" placeholder="请选择机构类型" clearable
          size="small" style="width: 170px !important">
          <el-option v-for="dict in dwlxLists" :key="dict.code" :label="dict.name" :value="dict.code" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="showType" label="机构托管类型">
        <el-input v-model="queryForm.contractType" disabled size="small"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
        <el-button size="small" type="primary" plain @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<style lang="scss" scoped>
.u-pl20 {
  padding-left: 20px;
}

.u-pt20 {
  padding-top: 20px;
}
</style>
